<template>
  <div>
    <el-date-picker v-model="recordDate" type="date" placeholder="选择日期" value-format="yyyy-MM-dd" style="width: 100%" :clearable="false" :picker-options="pickerOptions" @change="dateChange" />
    <br /><br />
    <el-timeline style="padding-left: 5px">
      <el-timeline-item v-if="hasClockIn" :timestamp="userCheckInfo.clockInDate" placement="top" color="#0bbd87">
        <p>上班打卡成功</p>
        <el-image style="width: 100px; height: 100px" :src="userCheckInfo.clockInMinPicUrl" :preview-src-list="[...userCheckInfo.clockInPicUrl]" />
      </el-timeline-item>
      <el-timeline-item v-else placement="top">
        <p>上班未打卡</p>
      </el-timeline-item>

      <el-timeline-item v-if="hasClockOut" :timestamp="userCheckInfo.clockOutDate" placement="top" color="#0bbd87">
        <p>下班打卡成功</p>
        <el-image style="width: 100px; height: 100px" :src="userCheckInfo.clockOutMinPicUrl" :preview-src-list="[...userCheckInfo.clockOutPicUrl]" />
      </el-timeline-item>
      <el-timeline-item v-else placement="top">
        <p>下班未打卡</p>
      </el-timeline-item>
    </el-timeline>

    <el-form v-if="!hasClockIn" ref="clockInForm" :model="form" label-position="top">
      <el-form-item label="上班图片">
        <el-button style="width: 124px; height: 124px; padding: 0" @click="galleryClockInImgUpload">
          <i v-if="clockInPercentage === 0" class="el-icon-plus" />
          <el-progress v-else-if="clockInPercentage !== 100" :width="100" style="width: 100; height: 100" type="circle" :percentage="clockInPercentage" :status="clockInProgressStatus" />
          <el-image v-else :src="clockInSrc" style="height: 95%; width: 95%" />
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 90%" :disabled="!form.picUrl" @click="clockInClick">上班打卡</el-button>
      </el-form-item>
    </el-form>

    <el-form v-if="hasClockIn && !hasClockOut" ref="clockOutForm" :model="form" label-position="top">
      <el-form-item label="下班图片">
        <el-button style="width: 124px; height: 124px; padding: 0" @click="galleryClockOutImgUpload">
          <i v-if="clockOutPercentage === 0" class="el-icon-plus" />
          <el-progress v-else-if="clockOutPercentage !== 100" :width="100" style="width: 100; height: 100" type="circle" :percentage="clockOutPercentage" :status="clockOutProgressStatus" />
          <el-image v-else :src="clockOutSrc" style="height: 95%; width: 95%" />
        </el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" style="width: 90%" :disabled="!form.picUrl" @click="clockOutClick">下班打卡</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { userCheckInfoUpload } from '@/api/upload.js';
import {
  userClockIn,
  userClockOut,
  getUserCheckInfoByDay,
} from "@/api/userCheckInfo.js";
export default {
  components: {},
  data() {
    return {
      pickerOptions: {}, // 日期设置对象
      recordDate: new Date(),
      form: {
        belongsDate: undefined,
        picUrl: undefined,
      },
      clockInSrc: undefined,
      clockOutSrc: undefined,
      hasClockIn: false,
      hasClockOut: false,
      userCheckInfo: {
        clockInDate: undefined,
        clockInPicUrl: undefined,
        clockInMinPicUrl: undefined,
        clockOutDate: undefined,
        clockOutPicUrl: undefined,
        clockOutMinPicUrl: undefined,
      },
      clockInPercentage: 0,
      clockInProgressStatus: "",
      clockOutPercentage: 0,
      clockOutProgressStatus: "",
      successCode: 20000,
    };
  },
  created() {
    this.getUserCheckInfo();
    this.pickerOptions.disabledDate = (time) => {
      // 设置可选择的日期为今天之后的一个月内
      const curDate = new Date().getTime();
      const day = 90 * 24 * 3600 * 1000;
      const dateRegion = curDate - day;
      return time.getTime() > Date.now() || time.getTime() < dateRegion;
    };
    // 扩展API是否准备好，如果没有则监听“plusready"事件
    if (window.plus) {
      this.plusReady();
    } else {
      document.addEventListener("plusready", this.plusReady, false);
    }
  },
  methods: {
    plusReady() {
      plus.webview.currentWebview();
    },

    cleanData() {
      this.form.picUrl = undefined;
      this.form.belongsDate = undefined;
      this.clockInSrc = undefined;
      this.clockOutSrc = undefined;
      this.hasClockIn = false;
      this.hasClockOut = false;
      this.userCheckInfo = {
        clockInDate: undefined,
        clockInPicUrl: undefined,
        clockInMinPicUrl: undefined,
        clockOutDate: undefined,
        clockOutPicUrl: undefined,
        clockOutMinPicUrl: undefined,
      };

      this.clockInPercentage = 0;
      this.clockInProgressStatus = "";
      this.clockOutPercentage = 0;
      this.clockOutProgressStatus = "";
    },

    dateChange() {
      this.cleanData();
      this.getUserCheckInfo();
    },

    // 根据日期获取打卡记录
    getUserCheckInfo() {
      getUserCheckInfoByDay(this.recordDate).then((response) => {
        if (response.code !== this.successCode) {
          return;
        }
        var data = response.datas[0];
        if (data === undefined) {
          return;
        }
        if (data.clockInDate) {
          this.userCheckInfo.clockInDate = data.clockInDate;
          this.hasClockIn = true;
          this.userCheckInfo.clockInPicUrl = process.env.VUE_APP_API_HOST + "/api/UserCheckInfo/" + data.clockInPicUrl;
          var suffixIndex = data.clockInPicUrl.lastIndexOf(".");
          if (suffixIndex >= 0) {
            this.userCheckInfo.clockInMinPicUrl = process.env.VUE_APP_API_HOST + "/api/UserCheckInfo/" +
              data.clockInPicUrl.substr(0, suffixIndex) + "_min" + data.clockInPicUrl.substr(suffixIndex);
          } else {
            this.userCheckInfo.clockInMinPicUrl = process.env.VUE_APP_API_HOST + "/api/UserCheckInfo/" + data.clockInPicUrl;
          }
        }
        if (data.clockOutDate) {
          this.userCheckInfo.clockOutDate = data.clockOutDate;
          this.hasClockOut = true;
          this.userCheckInfo.clockOutPicUrl = process.env.VUE_APP_API_HOST + "/api/UserCheckInfo/" + data.clockOutPicUrl;

          var suffixIndex = data.clockOutPicUrl.lastIndexOf(".");
          if (suffixIndex >= 0) {
            this.userCheckInfo.clockOutMinPicUrl = process.env.VUE_APP_API_HOST + "/api/UserCheckInfo/" +
              data.clockOutPicUrl.substr(0, suffixIndex) + "_min" + data.clockOutPicUrl.substr(suffixIndex);
          } else {
            this.userCheckInfo.clockOutMinPicUrl = process.env.VUE_APP_API_HOST + "/api/UserCheckInfo/" + data.clockOutPicUrl;
          }
        }
      });
    },

    // 上班打卡
    clockInClick() {
      if (!this.form.picUrl) {
        return;
      }
      this.form.belongsDate = this.recordDate;
      userClockIn(this.form).then((response) => {
        if (response.code === this.successCode) {
          this.cleanData();
          this.getUserCheckInfo();
        }
      });
    },

    // 下班打卡
    clockOutClick() {
      if (!this.form.picUrl) {
        return;
      }
      this.form.belongsDate = this.recordDate;
      userClockOut(this.form).then((response) => {
        if (response.code === this.successCode) {
          this.cleanData();
          this.getUserCheckInfo();
        }
      });
    },

    galleryClockInImgUpload() {
      var that = this;
      plus.gallery.pick(
        (filePath) => {
          that.clockInPercentage = 10;
          that.clockInProgressStatus = "";
          var suffixIndex = filePath.lastIndexOf(".");
          var suffix = "";
          if (suffixIndex >= 0) {
            suffix = filePath.substr(suffixIndex);
          }
          plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
            that.clockInPercentage = 15;
            entry.file(function (file) {
              var reader = new plus.io.FileReader();
              reader.onload = (e) => {
                that.clockInPercentage = 25;
                var arr = e.target.result.split(",");
                var mime = arr[0].match(/:(.*?);/)[1]; // 获取文件类型
                var bstr = atob(arr[1].replace(/\s/g, "")); //获取数据
                var n = bstr.length;
                var u8arr = new Uint8Array(n); //8 位无符号整数值的类型化数组
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n); //返回指定位置的字符的 Unicode编码 赋给数组指定位置
                }

                var blob = new Blob([u8arr], { type: mime });
                that.clockInPercentage = 40;

                userCheckInfoUpload(blob, file.name)
                  .then((response) => {
                    if (response.code !== that.successCode) {
                      that.clockInPercentage = 80;
                      that.clockInProgressStatus = "exception";
                      that.$notify({
                        title: "文件上传失败",
                        message: response.message,
                        type: "warning",
                        duration: 2000,
                      });
                    } else {
                      that.clockInPercentage = 100;
                      that.clockInProgressStatus = "success";
                      that.clockInSrc = URL.createObjectURL(blob);
                      that.form.picUrl = response.datas;
                    }
                  })
                  .catch(() => {
                    that.clockInPercentage = 80;
                    that.clockInProgressStatus = "exception";
                  });
              };
              reader.readAsDataURL(file);
            });
          });
        },
        function (a) { },
        {
          filter: "image",
          multiple: false,
        }
      );
    },

    galleryClockOutImgUpload() {
      var that = this;
      plus.gallery.pick(
        (filePath) => {
          that.clockOutPercentage = 10;
          that.clockOutProgressStatus = "";
          var suffixIndex = filePath.lastIndexOf(".");
          var suffix = "";
          if (suffixIndex >= 0) {
            suffix = filePath.substr(suffixIndex);
          }
          plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
            that.clockOutPercentage = 15;
            entry.file(function (file) {
              var reader = new plus.io.FileReader();
              reader.onload = (e) => {
                that.clockOutPercentage = 25;
                var arr = e.target.result.split(",");
                var mime = arr[0].match(/:(.*?);/)[1]; // 获取文件类型
                var bstr = atob(arr[1].replace(/\s/g, "")); //获取数据
                var n = bstr.length;
                var u8arr = new Uint8Array(n); //8 位无符号整数值的类型化数组
                while (n--) {
                  u8arr[n] = bstr.charCodeAt(n); //返回指定位置的字符的 Unicode编码 赋给数组指定位置
                }

                var blob = new Blob([u8arr], { type: mime });
                that.clockOutPercentage = 40;

                userCheckInfoUpload(blob, file.name)
                  .then((response) => {
                    if (response.code !== that.successCode) {
                      that.clockOutPercentage = 80;
                      that.clockOutProgressStatus = "exception";
                      that.$notify({
                        title: "文件上传失败",
                        message: response.message,
                        type: "warning",
                        duration: 2000,
                      });
                    } else {
                      that.clockOutPercentage = 100;
                      that.clockOutProgressStatus = "success";
                      that.clockOutSrc = URL.createObjectURL(blob);
                      that.form.picUrl = response.datas;
                    }
                  })
                  .catch(() => {
                    that.clockOutPercentage = 80;
                    that.clockOutProgressStatus = "exception";
                  });
              };
              reader.readAsDataURL(file);
            });
          });
        },
        function (a) { },
        {
          filter: "image",
          multiple: false,
        }
      );
    },
  },
};
</script>

<style>
.is-selected {
  color: #1989fa;
}
</style>
